package com.ruihu.admin.common.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.util.PoitlIOUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author: zhuoda
 * @create: 2020-03-31 08:54 PM from win10
 */

@Slf4j
public class BaseController {

    /**
     * 下载 Excel 消息头
     * @param fileName
     * @param workbook
     * @param response
     */
    public void downloadExcel(String fileName, Workbook workbook, HttpServletResponse response) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("", e);
        }
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        try {
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (IOException e) {
            log.error("", e);
        }
    }


    public void downloadWord(String fileName, XWPFDocument word, HttpServletResponse response) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("", e);
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".docx");
        try {
            word.write(response.getOutputStream());
            word.close();
        } catch (IOException e) {
            log.error("", e);
        }
    }

    public void downloadWord(String fileName, XWPFTemplate wordTemplate, HttpServletResponse response)  {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("", e);
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".docx");


        OutputStream os = null;
        BufferedOutputStream bos = null;
        try {
            os = response.getOutputStream();
//            FileOutputStream fos = new FileOutputStream("/home/test.docx");
            bos = new BufferedOutputStream(os);

            wordTemplate.write(bos);

            bos.flush();
            os.flush();
        } catch (IOException e) {
            log.error("", e);
        } finally {
            PoitlIOUtils.closeQuietlyMulti(wordTemplate, bos, os);
        }

    }

}
